/**
 * 医院AI助手组件
 * 集成医院导航和医疗咨询功能
 */

'use client'

import React, { useState, useEffect, useRef, useCallback } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Bot, Send, X, MapPin, Stethoscope, Calendar, Info } from 'lucide-react'
import { toast } from 'sonner'
import { getDepartmentsByHospital } from '@/lib/api/department'
import { getMedicalEquipmentByHospital } from '@/lib/api/medical-equipment'

interface AIMessage {
  id: string
  type: 'user' | 'assistant'
  content: string
  timestamp: Date
  actions?: Array<{
    type: 'navigate' | 'info' | 'appointment' | 'emergency'
    label: string
    data: any
  }>
}

interface HospitalAIAssistantProps {
  hospitalId?: string
  className?: string
  onNavigateTo?: (location: { lng: number; lat: number }) => void
  onDepartmentSelect?: (department: any) => void
  onBookAppointment?: (department: any) => void
}

export const HospitalAIAssistant: React.FC<HospitalAIAssistantProps> = ({
  hospitalId,
  className = '',
  onNavigateTo,
  onDepartmentSelect,
  onBookAppointment
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [activeBot, setActiveBot] = useState<'guide' | 'medical'>('guide')
  const [messages, setMessages] = useState<AIMessage[]>([])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [departments, setDepartments] = useState<any[]>([])
  const [equipment, setEquipment] = useState<any[]>([])
  const messagesEndRef = useRef<HTMLDivElement>(null)

  // AI响应模板 - 医院专用
  const aiResponses = {
    guide: {
      greeting: '您好！我是医院智能导航助手，可以帮您:\n• 🗺️ 科室导航\n• 🏥 设施查找\n• 📍 位置指引\n• ℹ️ 医院介绍\n\n请问需要什么帮助？',
      navigation: '我来为您导航到{location}，请跟随地图上的路线指示。',
      facility: '为您找到了{facility}的位置信息',
      info: '关于{topic}的详细信息如下',
      fallback: '抱歉，我没有完全理解您的问题。您可以询问科室位置、医院设施或就医指引等。'
    },
    medical: {
      greeting: '您好！我是医疗咨询助手，可以为您提供:\n• 👩‍⚕️ 科室介绍\n• 📅 挂号指导\n• 🩺 就医建议\n• 💊 用药提醒\n\n有什么可以帮您的吗？',
      appointment: '为您查询相关科室的挂号信息',
      consultation: '根据您的症状，建议您',
      medication: '关于用药的注意事项',
      fallback: '抱歉，我没有理解您的问题。您可以询问科室信息、挂号流程或就医建议等。'
    }
  }

  // 预设的科室关键词映射
  const departmentKeywords = {
    '急诊': {
      name: '急诊科',
      info: '🚑 急诊科 - 24小时急救服务\n\n📍 位置：医院一楼东侧\n⏰ 服务时间：24小时\n📞 急救电话：120\n\n🏥 主要服务：\n• 急性疾病救治\n• 外伤处理\n• 心肺复苏\n• 中毒抢救\n\n⚠️ 紧急情况请立即就诊！',
      type: 'emergency',
      location: { lng: 120.1551, lat: 30.2741 }
    },
    '内科': {
      name: '内科',
      info: '🩺 内科 - 内科疾病诊疗\n\n📍 位置：门诊楼二楼\n⏰ 门诊时间：8:00-17:30\n📞 咨询电话：0571-12345678\n\n🏥 主要服务：\n• 常见内科疾病\n• 慢性病管理\n• 健康体检\n• 用药指导\n\n💡 建议提前预约挂号',
      type: 'outpatient',
      location: { lng: 120.1552, lat: 30.2742 }
    },
    '外科': {
      name: '外科',
      info: '⚕️ 外科 - 外科疾病诊疗\n\n📍 位置：门诊楼三楼\n⏰ 门诊时间：8:00-17:30\n📞 咨询电话：0571-12345679\n\n🏥 主要服务：\n• 外科手术\n• 创伤处理\n• 肿瘤切除\n• 术后康复\n\n⚠️ 手术需提前预约',
      type: 'surgery',
      location: { lng: 120.1553, lat: 30.2743 }
    },
    '儿科': {
      name: '儿科',
      info: '👶 儿科 - 儿童专科医疗\n\n📍 位置：门诊楼四楼\n⏰ 门诊时间：8:00-17:30\n📞 咨询电话：0571-12345680\n\n🏥 主要服务：\n• 儿童常见病\n• 疫苗接种\n• 生长发育评估\n• 儿童保健\n\n👨‍👩‍👧‍👦 儿童就诊需家长陪同',
      type: 'outpatient',
      location: { lng: 120.1554, lat: 30.2744 }
    },
    '妇产科': {
      name: '妇产科',
      info: '👩 妇产科 - 妇女健康专科\n\n📍 位置：门诊楼五楼\n⏰ 门诊时间：8:00-17:30\n📞 咨询电话：0571-12345681\n\n🏥 主要服务：\n• 妇科疾病诊治\n• 产前检查\n• 分娩服务\n• 计划生育\n\n🤱 提供孕产妇全程服务',
      type: 'outpatient',
      location: { lng: 120.1555, lat: 30.2745 }
    }
  }

  // 设施关键词映射
  const facilityKeywords = {
    '卫生间': {
      name: '卫生间',
      info: '🚻 为您找到最近的卫生间\n\n📍 多个位置可选：\n• 门诊楼每层东西两侧\n• 住院楼各病区\n• 医技楼检查区域\n• 急诊科旁\n\n♿ 无障碍卫生间位于一楼大厅',
      type: 'toilet'
    },
    '电梯': {
      name: '电梯',
      info: '🛗 电梯位置信息\n\n📍 电梯分布：\n• 门诊楼：南北各2部\n• 住院楼：中央4部\n• 医技楼：东侧2部\n\n♿ 无障碍电梯：每栋楼至少1部\n🚑 医用电梯：住院楼专用',
      type: 'elevator'
    },
    '药房': {
      name: '药房',
      info: '💊 药房服务信息\n\n📍 位置：门诊楼一楼大厅\n⏰ 服务时间：7:30-21:00\n📞 咨询电话：0571-12345688\n\n🏥 服务项目：\n• 处方药调配\n• 用药指导\n• 药物咨询\n• 特殊药品管理\n\n💡 请持医生处方取药',
      type: 'pharmacy'
    }
  }

  // 加载医院数据
  const loadHospitalData = useCallback(async () => {
    if (!hospitalId) return

    try {
      const [departmentsResult, equipmentResult] = await Promise.all([
        getDepartmentsByHospital(hospitalId),
        getMedicalEquipmentByHospital(hospitalId)
      ])

      if (departmentsResult.success && departmentsResult.data) {
        setDepartments(departmentsResult.data)
      }

      if (equipmentResult.success && equipmentResult.data) {
        setEquipment(equipmentResult.data)
      }
    } catch (error) {
      console.error('加载医院数据失败:', error)
    }
  }, [hospitalId])

  useEffect(() => {
    loadHospitalData()
  }, [loadHospitalData])

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  // 初始化对话
  useEffect(() => {
    if (isOpen && messages.length === 0) {
      const welcomeMessage: AIMessage = {
        id: `msg_${Date.now()}`,
        type: 'assistant',
        content: aiResponses[activeBot].greeting,
        timestamp: new Date()
      }
      setMessages([welcomeMessage])
    }
  }, [isOpen, activeBot])

  // 智能意图识别
  const analyzeMessage = (message: string) => {
    const normalizedMessage = message.toLowerCase()
    
    // 科室查询意图
    for (const [keyword, deptInfo] of Object.entries(departmentKeywords)) {
      if (normalizedMessage.includes(keyword.toLowerCase())) {
        return {
          intent: 'department_query',
          entity: deptInfo,
          keyword
        }
      }
    }

    // 设施查询意图
    for (const [keyword, facilityInfo] of Object.entries(facilityKeywords)) {
      if (normalizedMessage.includes(keyword.toLowerCase()) || 
          normalizedMessage.includes(facilityInfo.name.toLowerCase())) {
        return {
          intent: 'facility_query',
          entity: facilityInfo,
          keyword
        }
      }
    }

    // 挂号预约意图
    if (normalizedMessage.includes('挂号') || normalizedMessage.includes('预约') || 
        normalizedMessage.includes('看病') || normalizedMessage.includes('就诊')) {
      return { intent: 'appointment', entity: null }
    }

    // 导航意图
    if (normalizedMessage.includes('在哪') || normalizedMessage.includes('怎么走') || 
        normalizedMessage.includes('位置') || normalizedMessage.includes('导航')) {
      return { intent: 'navigation', entity: null }
    }

    // 症状咨询意图
    if (normalizedMessage.includes('症状') || normalizedMessage.includes('疼痛') || 
        normalizedMessage.includes('不舒服') || normalizedMessage.includes('生病')) {
      return { intent: 'symptom_consultation', entity: null }
    }

    // 用药咨询意图
    if (normalizedMessage.includes('药') || normalizedMessage.includes('吃药') || 
        normalizedMessage.includes('用药') || normalizedMessage.includes('副作用')) {
      return { intent: 'medication_consultation', entity: null }
    }

    return { intent: 'unknown', entity: null }
  }

  // 生成AI响应
  const generateResponse = (message: string, analysis: any): AIMessage => {
    const { intent, entity, keyword } = analysis

    let content = ''
    let actions: any[] = []

    switch (intent) {
      case 'department_query':
        content = entity.info
        actions = [
          {
            type: 'navigate',
            label: '🗺️ 前往导航',
            data: entity.location
          },
          {
            type: 'appointment',
            label: '📅 预约挂号',
            data: entity
          },
          {
            type: 'info',
            label: 'ℹ️ 详细信息',
            data: entity
          }
        ]
        break

      case 'facility_query':
        content = entity.info
        const facility = equipment.find(e => e.type === entity.type)
        if (facility) {
          actions = [
            {
              type: 'navigate',
              label: '🗺️ 前往导航',
              data: { lng: facility.position[0], lat: facility.position[1] }
            }
          ]
        }
        break

      case 'appointment':
        if (activeBot === 'medical') {
          content = `${aiResponses.medical.appointment}\n\n📅 挂号方式：\n• 现场挂号：门诊楼一楼服务台\n• 网上预约：医院官网或APP\n• 电话预约：0571-12345666\n• 自助机：各楼层均有设置\n\n💡 建议提前1-7天预约，避免排队等候`
          
          const availableDepts = departments.slice(0, 3)
          actions = availableDepts.map(dept => ({
            type: 'appointment',
            label: `📅 ${dept.name}`,
            data: dept
          }))
        } else {
          content = '我是导航助手，如需挂号预约，请切换到医疗助手或前往一楼服务台。'
        }
        break

      case 'symptom_consultation':
        if (activeBot === 'medical') {
          content = `${aiResponses.medical.consultation}根据症状选择合适科室：\n\n🩺 常见症状科室指引：\n• 发热、咳嗽 → 内科\n• 外伤、疼痛 → 外科\n• 胸痛、心悸 → 心内科\n• 腹痛、消化不良 → 消化内科\n• 儿童症状 → 儿科\n\n⚠️ 紧急情况请直接前往急诊科`
        } else {
          content = '我是导航助手，如需症状咨询，请切换到医疗助手获得专业建议。'
        }
        break

      case 'medication_consultation':
        if (activeBot === 'medical') {
          content = `${aiResponses.medical.medication}：\n\n💊 用药安全提醒：\n• 严格按医嘱用药\n• 注意用药时间和剂量\n• 观察药物不良反应\n• 不可随意停药或换药\n\n🏥 用药咨询：\n• 药师咨询：门诊楼一楼药房\n• 咨询时间：7:30-21:00\n• 紧急情况：联系主治医生`
        } else {
          content = '我是导航助手，如需用药咨询，请切换到医疗助手或咨询药房药师。'
        }
        break

      case 'navigation':
        content = '请告诉我您想去的具体位置，比如"内科在哪"、"卫生间在哪里"等，我来为您导航。'
        break

      default:
        content = aiResponses[activeBot].fallback
        break
    }

    return {
      id: `msg_${Date.now()}_ai`,
      type: 'assistant',
      content,
      actions,
      timestamp: new Date()
    }
  }

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim()) return

    const userMessage: AIMessage = {
      id: `msg_${Date.now()}_user`,
      type: 'user',
      content: inputValue,
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setIsLoading(true)

    // 模拟AI处理时间
    setTimeout(() => {
      const analysis = analyzeMessage(inputValue)
      const aiResponse = generateResponse(inputValue, analysis)
      setMessages(prev => [...prev, aiResponse])
      setIsLoading(false)
    }, 1000)
  }

  // 处理快捷建议
  const handleSuggestionClick = (suggestion: string) => {
    setInputValue(suggestion)
    setTimeout(() => sendMessage(), 100)
  }

  // 处理动作按钮
  const handleActionClick = (action: any) => {
    switch (action.type) {
      case 'navigate':
        onNavigateTo?.(action.data)
        toast.success('正在为您导航...')
        break
      case 'info':
        onDepartmentSelect?.(action.data)
        break
      case 'appointment':
        onBookAppointment?.(action.data)
        toast.success('正在为您打开预约页面...')
        break
      case 'emergency':
        toast.error('紧急情况，请立即前往急诊科！')
        break
    }
  }

  // 切换机器人类型
  const switchBot = (bot: 'guide' | 'medical') => {
    setActiveBot(bot)
    setMessages([]) // 清空对话
  }

  // 快捷建议
  const getSuggestions = () => {
    if (activeBot === 'guide') {
      return ['内科在哪', '卫生间位置', '药房在几楼', '怎么去急诊科']
    } else {
      return ['我要挂号', '头痛挂什么科', '用药注意事项', '儿科怎么预约']
    }
  }

  if (!isOpen) {
    return (
      <div className={`fixed bottom-4 right-4 z-50 ${className}`}>
        <Button
          onClick={() => setIsOpen(true)}
          size="lg"
          className="rounded-full w-14 h-14 shadow-lg bg-gradient-to-r from-blue-500 to-green-600 hover:from-blue-600 hover:to-green-700"
        >
          <Bot className="w-6 h-6" />
        </Button>
      </div>
    )
  }

  return (
    <div className={`fixed bottom-4 right-4 w-96 h-[600px] bg-white rounded-lg shadow-2xl border z-50 flex flex-col ${className}`}>
      {/* 头部 */}
      <CardHeader className="pb-3 border-b">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg flex items-center gap-2">
            <Bot className="w-5 h-5" />
            医院AI助手
          </CardTitle>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setIsOpen(false)}
            className="h-8 w-8 p-0"
          >
            <X className="w-4 h-4" />
          </Button>
        </div>
        
        {/* 机器人切换 */}
        <Tabs value={activeBot} onValueChange={(value: any) => switchBot(value)} className="w-full">
          <TabsList className="grid w-full grid-cols-2 h-8">
            <TabsTrigger value="guide" className="text-xs gap-1">
              <MapPin className="w-3 h-3" />
              智能导航
            </TabsTrigger>
            <TabsTrigger value="medical" className="text-xs gap-1">
              <Stethoscope className="w-3 h-3" />
              医疗助手
            </TabsTrigger>
          </TabsList>
        </Tabs>
      </CardHeader>

      {/* 消息区域 */}
      <CardContent className="flex-1 overflow-y-auto p-4 space-y-3">
        {messages.map((message) => (
          <div
            key={message.id}
            className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
          >
            <div
              className={`max-w-[80%] p-3 rounded-lg text-sm ${
                message.type === 'user'
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-800'
              }`}
            >
              <div className="whitespace-pre-wrap">{message.content}</div>
              
              {/* 动作按钮 */}
              {message.actions && message.actions.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {message.actions.map((action, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      size="sm"
                      onClick={() => handleActionClick(action)}
                      className="h-6 px-2 text-xs"
                    >
                      {action.label}
                    </Button>
                  ))}
                </div>
              )}
              
              <div className="text-xs opacity-70 mt-1">
                {message.timestamp.toLocaleTimeString()}
              </div>
            </div>
          </div>
        ))}
        
        {isLoading && (
          <div className="flex justify-start">
            <div className="bg-gray-100 text-gray-800 p-3 rounded-lg text-sm">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" />
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }} />
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }} />
                <span>AI思考中...</span>
              </div>
            </div>
          </div>
        )}
        
        <div ref={messagesEndRef} />
      </CardContent>

      {/* 快捷建议 */}
      <div className="px-4 py-2 border-t bg-gray-50">
        <div className="text-xs text-gray-600 mb-2">快捷咨询：</div>
        <div className="flex flex-wrap gap-1">
          {getSuggestions().map((suggestion, index) => (
            <Button
              key={index}
              variant="outline"
              size="sm"
              onClick={() => handleSuggestionClick(suggestion)}
              className="h-6 px-2 text-xs"
            >
              {suggestion}
            </Button>
          ))}
        </div>
      </div>

      {/* 输入区域 */}
      <div className="p-4 border-t">
        <div className="flex gap-2">
          <Input
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder={`向${activeBot === 'guide' ? '导航助手' : '医疗助手'}提问...`}
            onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
            disabled={isLoading}
            className="flex-1"
          />
          <Button onClick={sendMessage} disabled={isLoading || !inputValue.trim()}>
            <Send className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </div>
  )
}